//==================================================================
//  Copyright (C) 2006-2007  Davide Pasca
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//==================================================================
///
///
///
///
//==================================================================

#ifndef PNETLIB_COMIOFILE_H
#define PNETLIB_COMIOFILE_H

#include "../../psys/include/psys.h"
#include "../../putils/include/memfile.h"
#include "pnetlib_com_basedef.h"

//==================================================================
class ComIOFile
{
public:
	int					_status;
	int					_fd;
	int					_einval_cnt;
	struct sockaddr_in	*_out_sap;

	u_char				*_outdatap;
	int					_outdata_size, _outdata_done;
	u_int				_outdata_ticket;

	bool				_indata_is_ready;
	PUtils::Memfile		_indata;

	ComIOFile();
	~ComIOFile();

	int		Connect( const char *ipnamep, int port_number );
	int		Idle();
	void	End();
	int		Send( void *datap, int size, u_int *send_ticketp );
	bool	IsDataSent( u_int send_ticket );
	bool	IsINDataReady() const
	{
		return _indata_is_ready;
	}

	// data in output has always \0\0 appended for eventual Unicode
	// string operations
	bool	GetINData( PUtils::Memfile* &out_indatap )
	{
		out_indatap = &_indata;
		return _indata_is_ready;
	}

	// data in output has always \0\0 appended for eventual Unicode
	// string operations
	bool	GetINDataStr( char *out_strp, int out_str_cnt )
	{
		int	len = _indata.GetDataSize();
		PASSERT( out_str_cnt >= (len+1) );

		for (int i=0; i < _indata.GetDataSize(); ++i)
			out_strp[i] = ((u_char *)_indata.GetData())[i];

		out_strp[ len ] = 0;

		return _indata_is_ready;
	}

		// data in output has always \0\0 appended for eventual Unicode
	// string operations
	u_int	GetINDataSize() const
	{
		return _indata.GetDataSize();
	}

private:
	int		on_disconnect( int printerror );
	int		handle_connecting();
	int		handle_send();
	int		handle_recv();
};

#endif

